/**
 * Created by Shaury on 2017/10/10.
 */
// import * as $ from "../../plugin/jquery-3.2.1/jquery-3.2.1.min";
var userDT = null;

$(document).ready(function () {
    var iRowSN = 1;
    // var userId = sessionStorage.getItem(userId);
    // var actorId = sessionStorage.getItem(actorId);
    userDT = $("#userDataTables").DataTable({
        "processing": true,
        "serverSide": true,
        "ordering": false,
        "displayLength": 20,
        "lengthMenu": [[20, 10, 15, 20, 50, 100, 150, -1], [20, 10, 15, 20, 50, 100, 150, "All"]],
        "ajax": {
            "url": "print_user/getAllUsers",
            "type": 'post',
            "data": function (d) {
                d.userDevice = "web";
                d.search = $('#userDataTables').DataTable().search(this.value);
            }
        },
        "columns": [{
            "data": "userId"
        }, {
            "data": "userName"
        }, {
            "data": "userPicUrl",
            "render": function (data, type, row) {
                if (data == null || data == "" || data == "undefined")
                    return "暂无";
                else
                    return "<img src='" + data + "' style='height: 90px;'>";
            }
        }, {
            "data": "userRealName"
        }, {
            "data": "userPhone"
        }, {
            "data": "usedMoney"
        }, {
            "data": "userId",
            "render": function (data, type, row, meta) {
                return "<button style='padding:0 10px;' class='btn btn-primary btn-xs' onclick='$.editForm(" + meta.row + ")'><span class='glyphicon glyphicon-edit' aria-hidden='true'></span>编辑</button>&nbsp;" +
                    "<button style='padding:0 10px;' class='btn btn-primary btn-xs' onclick='$.deleteUser(" + row.userId + ")'><span class='glyphicon glyphicon-trash' aria-hidden='true'></span>删除</button>"
            }
        }],
        "language": {
            "lengthMenu": "每页显示 _MENU_ 条记录",
            "zeroRecords": "没有符合条件的记录",
            "infoEmpty": "暂无数据",
            "processing": "<img src='pictures/others/loading.gif'/>加载中...",
            "info": "当前显示 _START_ 到 _END_ 条，共 _TOTAL_ 条记录",
            "infoFiltered": "(从 _MAX_ 条记录中过滤)",
            "search": "搜索",
            "paginate": {
                "first": "首页",
                "previous": "前一页",
                "next": "后一页",
                "last": "尾页"
            }
        },
        "dom": "<'row'<'col-md-2'l><'#userTool.col-md-10'>r>t<'row'<'col-md-6'i><'col-md-6'p>>",
        "initComplete": function () {
            $("#userTool").empty();
            $("#userTool").append("<button class='btn btn-success btn-sm' onclick='$.insertForm()'><span class='glyphicon glyphicon-camera' aria-hidden='true'></span> 添加用户</button>" +
                "<button id='search_button' style=' margin-left:10px;margin-top:4px;' class='btn btn-danger btn-sm pull-right' onclick='$(this).usersearchInfo()'>" +
                "<span class='glyphicon glyphicon-search' aria-hidden='true'></span></button><input style='width:20%;' type='text' class='form-control" +
                " pull-right' name='usersearchInfo' placeholder='用户名 / 姓名'>");
            $("input[name='usersearchInfo']").bind('keydown', function (event) {
                if (event.keyCode == "13") {
                    $(this).usersearchInfo();
                }
            });
        },
        "drawCallback" : function() {
            iRowSN = 1;
        },
        "rowCallback": function (row, data, displayIndex) {
            $('td:eq(0)', row).html($("#userDataTables").dataTable().fnSettings()._iDisplayStart + iRowSN++);
            return row;
        }
    });

    // 用自己的搜索框
    $.fn.usersearchInfo = function() {
        var search = $("input[name='usersearchInfo']").val().replace(/'/g, '');
        userDT.search(search).draw();
    }

    // 验证表单
    $('#userForm').bootstrapValidator({
        feedbackIcons : {
            valid : 'glyphicon glyphicon-ok',
            invalid : 'glyphicon glyphicon-remove',
            validating : 'glyphicon glyphicon-refresh'
        },
        fields : {
            userName : {
                validators : {
                    notEmpty : {
                        message : '用户名不能为空！'
                    }
                }
            },
            userRealName : {
                validators : {
                    notEmpty : {
                        message : '真实姓名不能为空！'
                    }
                }
            },
            userPhone : {
                validators : {
                    notEmpty : {
                        message : '手机号不能为空！'
                    },
                    stringLength: {
                        min: 11,
                        max: 11,
                        message: '请输入11位手机号！'
                    },
                    // regexp: {
                    //     regexp: /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/,
                    //     message: '请输入正确的手机号！'
                    // }
                }
            },
            userEmail : {
                validators : {
                    notEmpty : {
                        message : '邮箱不能为空！'
                    },
                    // emailAddress: {
                    //     message: '请输入正确的邮件地址如：12345@qq.com'
                    // }
                }
            },
            userSchool : {
                validators : {
                    notEmpty : {
                        message : '学校不能为空！'
                    }
                }
            },
        }
    }).on('success.form.bv', function(e) {
        e.preventDefault();
        var formData = $("#userForm").serialize();
        var sFormAction = "print_user/insertUserInfo";
        /*如果是编辑模式，则添加一步　加入id信息 同时更新url*/
        if (editFlag) {
            sFormAction = "print_user/updateUserInfo";
            formData += "&userId=" + $("#userModal").data("userId");
        }
        var userPicUrl = "";
        if($("#addUserPic").attr("src") != "pictures/others/nopicTip.png"){
            userPicUrl = $("#addUserPic").attr("src");
        }
        formData += "&userPicUrl=" + userPicUrl;
        $.ajax({
            type : 'post',
            dataType : 'json',
            data : formData,
            url : sFormAction,
            success : function(result) {
                if(result.ajaxInfo == "Success")
                {
                    alert('更新或插入成功');
                    $('#userForm').bootstrapValidator('resetForm', true);
                    $("#userModal").modal("hide");
                    userDT.ajax.reload(null,false)
                }else{
                    alert("更新或插入失败");
                    userDT.ajax.reload(null,false)
                }
            }
        });
    });
    // 隐藏模态框后，执行
    $("#userModal").on("hide.bs.modal", function() {
        $("#userForm").data("bootstrapValidator").resetForm(); // 取消验证信息
        $("#userForm").resetForm();
        $(this).removeData("userId");
    });

    var editFlag=false;

    /*新增信息*/
    $.insertForm = function() {
        $("#userLable").html("添加用户");
        editFlag = false;
        $("img[name='addUserPic']").attr("src","pictures/others/nopicTip.png");
        // $("select[name='userType']").val("1");
        // $("#passConfirmDiv").show();
        // $("#reportOrderMark").hide();
        $("#userModal").modal({
            backdrop : 'static',
            keyboard : false,
            show : true
        });
    }

    /*编辑信息*/
    $.editForm = function(rowindex) {
        var jsonData = userDT.row(rowindex).data();
        if (jsonData.userPicUrl != null && jsonData.userPicUrl != "")
            $("img[name='addUserPic']").attr("src", jsonData.userPicUrl);
        else
            $("img[name='addUserPic']").attr("src", "pictures/others/nopicTip.png");
        if(jsonData != null){
            $("#userModal").data("userId",jsonData.userId);
            $("input[name='userName']").val(jsonData.userName);
            $("input[name='userRealName']").val(jsonData.userRealName);
            $("input[name='userPhone']").val(jsonData.userPhone);
            $("input[name='userEmail']").val(jsonData.userEmail);
            $("input[name='userIntegral']").val(jsonData.userIntegral);
            $("input[name='usedMoney']").val(jsonData.usedMoney);
            $("input[name='userSchool']").val(jsonData.userSchool);
            $("input[name='userCode']").val(jsonData.userCode);
            editFlag = true;
            $("#userLable").html("编辑用户");
            $("#userModal").modal({
                backdrop : 'static',
                keyboard : false,
                show : true
            });
        }
    }

    $.deleteUser = function(userId){
        bootbox.confirm({
            buttons: {
                confirm: {
                    label: '确认',
                    className: 'btn-info'
                },
                cancel: {
                    label: '取消',
                    className: 'btn-default'
                }
            },
            title: '提示',
            message: '确定删除么？',
            callback: function(result) {
                if(result)
                {
                    $.ajax({
                        type : "post",
                        data : {
                            "userDevice":"web",
                            "userId" : userId,
                        },
                        dataType : "json",
                        url : "print_user/deleteUser",
                        success : function(msg){
                            if(msg.ajaxInfo == "Success")
                            {
                                alert("删除成功！");
                                userDT.ajax.reload(null,false);
                            }
                            else
                            {
                                alert("操作失败！");
                            }
                        }
                    });
                }
            }
        });
    }

    // 当密码修改时，显示密码确认框
    $("input[name='userPass']").bind('input propertychange', function() {
        $("input[name='passConfirm']").val("");
        $("#passConfirmDiv").show();
    });

    //当人物属性框发生变化时，选择是否显示小记者编辑框
    $("#selectId").bind('input propertychange',function() {
        if( $("#selectId").val()==2){
            $("#reportOrderMark").show();
        }
        else{
            $("#reportOrderMark").hide();
        }
    })
});

// 接收键盘enter,模拟点击search_button
function keyDown(e) {
    var keycode = e.which;
    var realkey = String.fromCharCode(e.which);
    if (keycode == 13) {
        $("#search_button").click();
    }
}
document.onkeydown = keyDown;

